package person.wend.javalearnexample.util.concurrent.executor;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPoolExecutorExample {
    public static void main(String[] args) throws InterruptedException {
        // 创建一个 ScheduledThreadPoolExecutor 实例
        ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(2);

        // 安排一个任务，在2秒后执行一次
        scheduler.schedule(() -> System.out.println("Scheduled Task executed"), 2, TimeUnit.SECONDS);

        // 安排一个周期性任务，首次执行延迟1秒，之后每隔3秒执行一次
        scheduler.scheduleAtFixedRate(() -> System.out.println("Periodic Task executed"), 1, 3, TimeUnit.SECONDS);

        // 让主线程稍微等待一下，以便观察调度任务的输出
        Thread.sleep(10000);

        // 关闭调度线程池
        scheduler.shutdown();
        if (!scheduler.awaitTermination(60, TimeUnit.SECONDS)) {
            scheduler.shutdownNow();
        }
    }
}
